#include "reader.h"
#include "randomgenerator.h"
#include <QFuture>
#include <QDebug>
#include "shelf.h"

Reader::Reader(int readInterval, QObject* parent) :
    interval(readInterval), QRunnable(), QObject(parent)
{
}

void Reader::run()
{
    while(true)
    {
        shelf::abilityToChange.lock();
        size_t size = shelf::books.size();
        shelf::abilityToChange.unlock();
        if (size > 0) {
            int curBook = qrand() % size;
            if(curBook < 0 || curBook >= size) {
                qDebug() << "fail " << curBook;
                continue;
            }
            qDebug() << "try read " << curBook << " " << size;
            shelf::abilityToChange.lock();
            if (!shelf::books[curBook])
            {
                shelf::abilityToChange.unlock();
                continue;
            }
            shelf::books[curBook] = false;
            shelf::abilityToChange.unlock();
            qDebug() << "read " << curBook;
            sleep(interval);
            qDebug() << "reader puts " << curBook;
            shelf::abilityToChange.lock();
            shelf::books[curBook] = true;
            shelf::abilityToChange.unlock();
        }
    }
}
